import { defineStore } from 'pinia';
import { ref } from 'vue';
import {
  GetAppointmentList,
  AppointmentListAdd,
  AppointmentListCancel,
} from '@/api/api.js';
import { useShopStore } from '@/store/shop';
import { delay } from '@/tools/tools';

export const useAppointmentStore = defineStore('appointment', () => {
  const historyAppointments = ref([]);

  async function getHistoryAppointments() {
    const shopStore = useShopStore();
    const data = await GetAppointmentList(
      shopStore.longitude,
      shopStore.latitude,
    );
    historyAppointments.value = data;
  }
  async function addAppointment(...params) {
    try {
      uni.showLoading({
        title: '预约中...',
      });
      await AppointmentListAdd(...params);
      await getHistoryAppointments();
      uni.showToast({
        title: '预约成功',
      });
      await delay(1000);
      uni.navigateBack();
    } catch (error) {
      console.error('addAppointment error', error);
      uni.showToast({
        title: error || '预约失败',
        icon: 'none',
      });
    }
  }
  async function cancelAppointment(RecId) {
    uni.showLoading({
      title: '取消中...',
    });
    await AppointmentListCancel(RecId);
    await getHistoryAppointments();
    uni.showToast({
      title: '取消成功',
    });
  }

  return {
    historyAppointments,
    getHistoryAppointments,
    addAppointment,
    cancelAppointment,
  };
});
